package com.jza04.flightbooking.controller;

import com.jza04.flightbooking.entity.Flight;
import com.jza04.flightbooking.entity.Passenger;
import com.jza04.flightbooking.entity.Ticket;
import com.jza04.flightbooking.entity.Discount;
import com.jza04.flightbooking.service.FlightService;
import com.jza04.flightbooking.service.PassengerService;
import com.jza04.flightbooking.service.TicketService;
import com.jza04.flightbooking.service.DiscountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 购票控制器
 */
@Controller
@RequestMapping("/tickets")
public class TicketController {

    @Autowired
    private TicketService ticketService;
    
    @Autowired
    private FlightService flightService;
    
    @Autowired
    private PassengerService passengerService;
    
    @Autowired
    private DiscountService discountService;
    
    /**
     * 查询所有购票记录
     */
    @GetMapping
    public String listAllTickets(Model model) {
        model.addAttribute("tickets", ticketService.findAllTickets());
        return "ticket/list";
    }
    
    /**
     * 获取票数统计
     */
    @GetMapping("/count")
    @ResponseBody
    public Integer getTicketCount() {
        return ticketService.findAllTickets().size();
    }
    
    /**
     * 查看购票详情
     */
    @GetMapping("/{ticketId}")
    public String viewTicket(@PathVariable Integer ticketId, Model model) {
        model.addAttribute("ticket", ticketService.findTicketById(ticketId));
        return "ticket/view";
    }
    
    /**
     * 显示购票表单
     */
    @GetMapping("/book/{flightId}")
    public String showBookForm(@PathVariable String flightId, Model model) {
        Flight flight = flightService.findFlightById(flightId);
        if (flight == null || flight.getRemainingSeats() <= 0) {
            return "redirect:/flights";
        }
        
        // 创建新的购票记录
        Ticket ticket = new Ticket();
        ticket.setFlightId(flightId);
        ticket.setFlight(flight);
        
        // 加载有效的折扣
        List<Discount> validDiscounts = discountService.findValidDiscounts();
        
        model.addAttribute("ticket", ticket);
        model.addAttribute("flight", flight);
        model.addAttribute("passengers", passengerService.findAllPassengers());
        model.addAttribute("discounts", validDiscounts);
        return "ticket/book";
    }
    
    /**
     * 处理购票请求
     */
    @PostMapping("/book")
    public String bookTicket(Ticket ticket, @RequestParam("passengerId") Integer passengerId, 
                           @RequestParam(value = "discountId", required = false) Integer discountId) {
        
        // 获取旅客信息
        Passenger passenger = passengerService.findPassengerById(passengerId);
        if (passenger == null) {
            return "redirect:/flights";
        }
        
        ticket.setPassengerId(passengerId);
        ticket.setPurchaseDate(new Date());
        
        // 计算实际票价
        Flight flight = flightService.findFlightById(ticket.getFlightId());
        BigDecimal actualPrice = flight.getBasePrice();
        
        // 应用折扣
        if (discountId != null) {
            Discount discount = discountService.findDiscountById(discountId);
            if (discount != null) {
                ticket.setDiscountId(discountId);
                // 应用折扣
                actualPrice = actualPrice.multiply(discount.getDiscountRate());
            }
        }
        
        // 应用VIP折扣
        if (passenger.getVipDiscount() != null) {
            actualPrice = actualPrice.multiply(passenger.getVipDiscount());
        }
        
        ticket.setActualPrice(actualPrice);
        
        // 完成购票
        ticketService.bookTicket(ticket);
        
        return "redirect:/tickets";
    }
    
    /**
     * 取消购票
     */
    @GetMapping("/cancel/{ticketId}")
    public String cancelTicket(@PathVariable Integer ticketId) {
        ticketService.cancelTicket(ticketId);
        return "redirect:/tickets";
    }
    
    /**
     * 更新票状态
     */
    @PostMapping("/status/{ticketId}")
    public String updateTicketStatus(@PathVariable Integer ticketId, @RequestParam String status) {
        ticketService.updateTicketStatus(ticketId, status);
        return "redirect:/tickets/" + ticketId;
    }
    
    /**
     * 打印票据
     */
    @GetMapping("/print/{ticketId}")
    public String printTicket(@PathVariable Integer ticketId, Model model) {
        Ticket ticket = ticketService.findTicketById(ticketId);
        if (ticket == null) {
            return "redirect:/tickets";
        }
        model.addAttribute("ticket", ticket);
        return "ticket/print";
    }
    
    /**
     * 确认出票
     */
    @GetMapping("/issue/{ticketId}")
    public String issueTicket(@PathVariable Integer ticketId) {
        Ticket ticket = ticketService.findTicketById(ticketId);
        if (ticket != null && "已预订".equals(ticket.getStatus())) {
            ticketService.updateTicketStatus(ticketId, "已出票");
        }
        return "redirect:/tickets/" + ticketId;
    }
    
    /**
     * 标记已使用
     */
    @GetMapping("/check-in/{ticketId}")
    public String checkInTicket(@PathVariable Integer ticketId) {
        Ticket ticket = ticketService.findTicketById(ticketId);
        if (ticket != null && "已出票".equals(ticket.getStatus())) {
            ticketService.updateTicketStatus(ticketId, "已使用");
        }
        return "redirect:/tickets/" + ticketId;
    }
}